<script>
import { getMaterialMediaId, getList, addSend } from '@/api/chat'
import NoData from '@/components/NoData.vue'
export default {
  components: { NoData },
  props: {
    sideId: {
      type: String,
      default: '',
    },
    // mediaType 0 图片（image）、1 语音（voice）、2 视频（video），3 普通文件(file) 4 文本 5 海报
    mediaType: {
      type: String,
      default: null,
    },
    // keyword: {
    //   type: String,
    //   default: '',
    // },
  },
  data() {
    return {
      userName: '',
      refreshing: false,
      loading: false,
      finished: false,
      finishedText: '暂无数据',
      keyword: undefined,
      error: false,
      pageSize: 10,
      list: [],
      collectList: [],
      // 查询条件
      query: {
        pageNum: 1,
        pageSize: 10,
        materialName: '',
        mediaType: '',
      },
      clickObj: null, // 点击的列表的时候传的对象
      categoryId: null,
      show: false,
    }
  },
  watch: {
    userId() {
      this.sideId || this.getList(1)
    },
  },
  computed: {
    userId() {
      return this.$store.state.userId
    },
  },
  created() {
    this.getList()
    this.sysId = sessionStorage.getItem('sysId')
  },
  mounted() {},
  methods: {
    // 处理文件类型
    filType(file) {
      let filecontent = JSON.parse(JSON.stringify(file))
      filecontent = filecontent.split('.')
      let type = filecontent[filecontent.length - 1]
      if (type === 'pdf') {
        return 'pdf'
      } else if (type === 'doc' || type === 'docx') {
        return 'word'
      } else if (type === 'ppt' || type === 'pptx' || type === 'pps' || type === 'pptsx') {
        return 'ppt'
      } else {
        return ''
      }
    },
    filPicType(file) {
      let filecontent = JSON.parse(JSON.stringify(file))
      filecontent = filecontent.split('.')
      let type = filecontent[filecontent.length - 1]
      if (type === 'pdf') {
        return window.lwConfig.DEFAULT_H5_PDF
      } else if (['doc', 'docx'].includes(type)) {
        return window.lwConfig.DEFAULT_H5_WORDE
      } else if (['ppt', 'pptx', 'pps', 'pptsx'].includes(type)) {
        return window.lwConfig.DEFAULT_H5_PPT
      } else {
        return ''
      }
    },
    showPopup(obj) {
      if (['4', '0'].includes(obj.mediaType)) {
        this.show = true
        this.clickObj = { ...obj }
      }
    },
    getList(page) {
      this.loading = true
      this.finished = false
      let pageSize = this.pageSize

      // if (this.categoryId) {
      //   this.query.categoryId = this.categoryId
      // }
      this.query.mediaType = this.mediaType
      this.query.materialName = this.keyword
      this.query.pageSize = pageSize
      page && (this.query.pageNum = page)
      getList(this.query)
        .then(({ rows, total }) => {
          if (this.query.pageNum == 1) {
            this.list = []
          }
          this.list.push(...rows)
          this.loading = false
          this.refreshing = false
          // 数据全部加载完成
          if (this.list.length >= +total) {
            if (this.list.length == 0) {
              this.query.pageNum = 1
              this.finishedText = ''
            } else {
              this.finishedText = '没有更多了'
            }
            this.finished = true
          } else {
            this.query.pageNum++
          }
        })
        .catch(() => {
          this.error = true
          this.loading = false
        })
    },
    search(pageNum, keyword, categoryId) {
      this.keyword = keyword
      if (categoryId) {
        this.query.categoryId = categoryId
      } else {
        delete this.query.categoryId
      }
      this.getList(pageNum)
    },
    preview(obj) {
      if (obj.id !== '0' && obj.id !== '4') {
        this.$router.push({
          name: 'metrialDetail',
          query: {
            materiaId: obj.id,
            isBack: true,
          },
        })
      }
    },
    // 统计发送次数
    addSend(data) {
      this.userName = sessionStorage.getItem('userName')
      let obj = {
        contentId: data.id,
        sendBy: this.userName,
        sendById: this.sysId,
        resourceType: 1,
      }
      addSend(obj).then((res) => {
        console.log(res)
      })
    },
    send(data) {
      this.$toast.loading({
        message: '正在发送...',
        duration: 0,
        forbidClick: true,
      })
      let entry = undefined
      let _this = this
      wx.invoke('getContext', {}, async function(res) {
        if (res.err_msg == 'getContext:ok') {
          entry = res.entry //返回进入H5页面的入口类型，目前 contact_profile、single_chat_tools、group_chat_tools
          let mes = {}
          try {
            if (!['single_chat_tools', 'group_chat_tools', 'normal'].includes(entry)) {
              // _this.$toast.clear()
              _this.$toast('入口错误：' + entry)
              return
            }

            // mediaType 0 图片（image）、1 语音（voice）、2 视频（video），3 普通文件(file) 4 文本 5 海报
            // msgtype 文本(“text”)，图片(“image”)，视频(“video”)，文件(“file”)，H5(“news”）和小程序(“miniprogram”)

            let msgtype = {
              0: 'image',
              2: 'news',
              3: 'news',
              4: 'text',
              5: 'news',
              9: 'news',
              11: 'miniprogram',
              12: 'news',
              18: 'news',
              19: 'news',
            }

            let linkUrl =
              window.document.location.origin +
              window.lwConfig.BASE_URL +
              '#/metrialDetail?materiaId=' +
              data.id +
              '&userId=' +
              sessionStorage.getItem('sysId')
            switch (data.mediaType) {
              case '4':
              default:
                mes.text = {
                  content: data.content ? data.content : '', //文本内容
                }
                break
              case '0':
                let dataMediaId = {
                  url: data.materialUrl,
                  type: msgtype[data.mediaType],
                  name: data.materialName,
                }
                try {
                  let resMaterialId = await getMaterialMediaId(dataMediaId)
                  if (!resMaterialId.data) {
                    _this.$toast('获取素材id失败')
                    return
                  }
                  mes[msgtype[data.mediaType]] = {
                    mediaid: resMaterialId.data.mediaId, //
                  }
                } catch (error) {
                  return
                }
                break
              // 图文
              case '9':
                mes.news = {
                  link: data.materialUrl ? data.materialUrl : ' ', //H5消息页面url 必填
                  title: data.materialName ? data.materialName : ' ', //H5消息标题
                  desc: data.content ? data.content : ' ', //H5消息摘要
                  imgUrl: data.coverUrl || window.lwConfig.DEFAULT_H5_PIC, //H5消息封面图片URL
                }
                break
              // 视频 文章 外链
              case '2':
              case '12':
              case '19':
                mes.news = {
                  link: linkUrl, //H5消息页面url 必填
                  title: data.materialName ? data.materialName : ' ', //H5消息标题
                  desc: data.digest || data.content, //H5消息摘要
                  imgUrl: data.coverUrl || window.lwConfig.DEFAULT_H5_PIC, //H5消息封面图片URL
                }
                break
              // 文件
              case '3':
                mes.news = {
                  link: linkUrl, //H5消息页面url 必填
                  title: data.materialName ? data.materialName : ' ', //H5消息标题
                  desc: data.digest ? data.digest : ' ', //H5消息摘要
                  imgUrl: _this.filPicType(data.materialUrl), //H5消息封面图片URL
                }
                break
              // 海报
              case '5':
                mes.news = {
                  link: linkUrl, //H5消息页面url 必填
                  title: data.materialName ? data.materialName : ' ', //H5消息标题
                  desc: data.digest ? data.digest : ' ', //H5消息摘要
                  imgUrl: data.materialUrl || window.lwConfig.DEFAULT_H5_PIC, //H5消息封面图片URL
                }
                break
              // 收集表
              case '18':
                mes.news = {
                  // link: linkUrl, //H5消息页面url 必填
                  link: data.materialUrl ? data.materialUrl : ' ', //H5消息页面url 必填
                  title: data.materialName ? data.materialName : ' ', //H5消息标题
                  desc: data.digest ? data.digest : ' ', //H5消息摘要
                  imgUrl: window.lwConfig.DEFAULT_H5_COLLECT, //H5消息封面图片URL
                }
                break
              case '11':
                mes.miniprogram = {
                  appid: data.digest ? data.digest : ' ', //小程序的appid
                  title: data.materialName ? data.materialName : ' ', //小程序消息的title
                  imgUrl: data.coverUrl ? data.coverUrl : ' ', //小程序消息的封面图。必须带http或者https协议头，否则报错 $apiName$:fail invalid imgUrl
                  page: data.materialUrl ? data.materialUrl : ' ', //小程序消息打开后的路径，注意要以.html作为后缀，否则在微信端打开会提示找不到页面
                }
                break
            }
            mes.msgtype = msgtype[data.mediaType]
            // _this.$dialog({ message: 'mes：' + JSON.stringify(mes) })
          } catch (err) {
            _this.$dialog({ message: 'err' + JSON.stringify(err) })
          }
          wx.invoke('sendChatMessage', mes, function(resSend) {
            if (resSend.err_msg == 'sendChatMessage:ok') {
              //发送成功 sdk会自动弹出成功提示，无需再加
              // _this.$toast('发送成功')
              _this.addSend(data)
            }
            if ('sendChatMessage:cancel,sendChatMessage:ok'.indexOf(resSend.err_msg) < 0) {
              //错误处理
              let err_msg = JSON.stringify(resSend.err_msg)
              if (err_msg === '"sendChatMessage:fail, not allow to cross corp"') {
                _this.$dialog({ message: '发送失败：' + '小程序配置有误' })
              } else {
                _this.$dialog({ message: '发送失败：' + JSON.stringify(resSend) })
              }
            }
          })
          _this.$toast.clear()
        } else {
          _this.$toast.clear()
          //错误处理
          _this.$dialog({ message: '进入失败：' + JSON.stringify(res) })
        }
      })
    },
    // collect(data) {
    //   this.$toast.loading({
    //     message: 'loading...',
    //     duration: 0,
    //     forbidClick: true,
    //   })
    //   // collection 是否收藏 0未收藏 1 已收藏
    //   ;(data.collection == 1 ? cancleCollection : addCollection)({
    //     userId: this.userId,
    //     materialId: data.materialId,
    //   })
    //     .then(() => {
    //       data.collection = [1, 0][data.collection]
    //       this.$toast('操作成功')
    //       this.$emit('collect')
    //     })
    //     .catch((err) => {
    //       this.$toast('操作失败')
    //       console.log(err)
    //     })
    // },
  },
}
</script>

<template>
  <div>
    <van-pull-refresh v-model="refreshing" success-text="刷新成功" @refresh="getList(1)">
      <van-list
        v-model="loading"
        :finished="finished"
        :finished-text="finishedText"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="getList()"
      >
        <NoData v-if="!loading && (!list || !list.length)" />
        <div v-for="(item, index) in list" class="itemList" :key="index">
          <div class="content bfc-o" @click="showPopup(item)">
            <div class="title" v-if="item.mediaType !== '18'">{{ item.materialName }}</div>
            <!-- 文本 -->
            <p class="text" v-if="item.mediaType == '4'">{{ item.content }}</p>
            <!-- 图片 -->
            <!-- <van-image
              v-if="[0, 5].includes(+item.mediaType)"
              width="80"
              height="80"
              :src="item.materialUrl"
            /> -->
            <van-image
              v-if="item.mediaType == '0' && item.materialUrl"
              width="50"
              height="50"
              :src="item.materialUrl"
            />
            <div class="icon-style" v-if="item.mediaType == '0' && !item.materialUrl">
              <svg-icon class="icon-style" name="pic"></svg-icon>
            </div>
            <!-- 图文 -->
            <div class="centerStyle" v-if="item.mediaType == 9">
              <van-image width="50" height="50" :src="item.coverUrl" v-if="item.coverUrl" />
              <div class="icon-style" v-else>
                <svg-icon class="icon-style" name="imgText"></svg-icon>
              </div>
              <div class="contentStyle">{{ item.content }}</div>
            </div>
            <!-- 小程序 -->
            <div class="centerStyle" v-if="item.mediaType == 11">
              <van-image width="50" height="50" :src="item.coverUrl" v-if="item.coverUrl" />
              <div class="icon-style" v-else>
                <svg-icon class="icon-style" name="pic"></svg-icon>
              </div>
            </div>

            <!-- 文章 -->
            <div class="centerStyle" v-if="item.mediaType == 12">
              <van-image width="50" height="50" :src="item.coverUrl" v-if="item.coverUrl" />
              <div class="icon-style" v-else>
                <svg-icon class="icon-style" name="article"></svg-icon>
              </div>
              <div class="contentStyle">{{ item.digest }}</div>
            </div>
            <!-- 视频 -->
            <div class="centerStyle" v-if="item.mediaType == 2">
              <van-image width="50" height="50" :src="item.coverUrl" />
              <div class="contentStyle">{{ item.digest }}</div>
            </div>
            <!-- 海报 -->
            <div class="centerStyle" v-if="item.mediaType == 5">
              <van-image width="50" height="50" :src="item.materialUrl" v-if="item.materialUrl" />
              <div class="icon-style" v-else>
                <svg-icon class="icon-style" name="pic"></svg-icon>
              </div>
              <div class="contentStyle">{{ item.digest }}</div>
            </div>
            <!-- 文件 -->
            <div style="display: flex;" v-if="item.mediaType === '3'">
              <div v-if="item.materialUrl" class="icon-style">
                <svg-icon class="icon-style" :name="item.materialUrl ? filType(item.materialUrl) : ''"></svg-icon>
              </div>
              <div class="contentStyle">{{ item.digest }}</div>
            </div>
            <!-- 收集表 -->
            <div style="display: flex;" v-if="item.mediaType === '18'">
              <div class="icon-style">
                <svg-icon class="icon-style" name="collect"></svg-icon>
              </div>
              <div class="contentTitle">{{ item.materialName }}</div>
              <!-- <div class="contentStyle">{{ item.digest }}</div> -->
            </div>
            <!-- 视频 -->
            <!-- <video
              v-if="item.mediaType == 2"
              class="video"
              controls
              webkit-playsinline="true"
              playsinline="true"
              :autoplay="false"
              preload="auto"
              :poster="item.coverUrl"
            >
              <source :src="item.materialUrl" type="video/mp4" />
            </video> -->
            <!-- <van-image v-if="item.mediaType == 2" width="50" height="50" :src="item.coverUrl" /> -->
          </div>
          <div class="info">
            <!-- {{ mediaTypeObj[item.mediaType] }}类型
            <span class="time">{{ item.createTime }}</span> -->

            <div class="flex fr">
              <div
                v-if="
                  item.mediaType !== '0' &&
                    item.mediaType !== '4' &&
                    item.mediaType !== '11' &&
                    item.mediaType !== '3' &&
                    item.mediaType !== '18'
                "
                class="preview"
                @click="preview(item)"
              >
                预览
              </div>
              <!-- 文件 -->
              <a target="_blank" :href="item.materialUrl" class="preview" v-if="item.mediaType == '3'">预览</a>
              <div class="action" @click="send(item)">发送</div>
              <!-- <div v-if="!!userId" class="action" @click="collect(item)">
                {{ item.collection == 1 ? '取消' : '' }}收藏
              </div> -->
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <van-popup v-model="show" closeable round>
      <div class="popText" v-if="mediaType == '4'">
        <div class="popTitle">{{ clickObj ? clickObj.materialName : '' }}</div>
        <div class="popContent">
          {{ clickObj ? clickObj.content : '' }}
        </div>
      </div>
      <div class="popPic" v-if="mediaType == '0'">
        <van-image width="200" :src="clickObj ? clickObj.materialUrl : ''" />
      </div>
    </van-popup>
  </div>
</template>

<style lang="less" scoped>
.icon-style {
  width: 50px;
  height: 50px;
  margin-right: 6px;
}
.info {
  height: 20px;
}
.itemList {
  width: 90%;
  margin: 10px;
  background-color: #fff;
  margin-bottom: 0px;
  padding: 10px;
  border-radius: 4px;
}
.content {
  .van-image,
  .video {
    float: left;
    width: 80px;
    height: 80px;
    margin: 0 10px 5px 0;
    border: 1px solid #eee;
  }
  .text {
    font-size: 12px;
    color: #000;
    // word-break: break-all;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    margin-bottom: 6px;
    white-space: pre-line;
  }
}
.time {
  margin-left: 5px;
}
.title {
  font-weight: 700;
  font-size: 12px;
  color: #333;
  line-height: 18px;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 6px;
}
.centerStyle {
  display: flex;
  width: 100%;
  justify-content: space-between;
}
.contentTitle {
  font-weight: 700;
  font-size: 12px;
  color: #333;
  line-height: 18px;
  width: calc(100% - 60px);
  // white-space: nowrap;
  // overflow: hidden;
  // text-overflow: ellipsis;
  // margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  // margin-top: 20px;
  align-items: top;
}
.contentStyle {
  font-size: 12px;
  color: #aaaaaa;
  width: calc(100% - 60px);
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  // margin-top: 20px;
  align-items: top;
}
.popText {
  padding: 20px;
  width: 300px;
  .popTitle {
    color: #000;
    font-size: 14px;
    width: 90%;
    // margin-top: 20px;
    margin-bottom: 20px;
    line-height: 18px;
  }
  .popContent {
    width: 100%;
    max-height: 300px;
    min-height: 40px;
    overflow-y: auto;
    color: #333;
    font-size: 14px;
    line-height: 18px;
    white-space: pre-line;
  }
}
.popPic {
  padding: 40px;
}
.action {
  width: 50px;
  height: 20px;
  font-size: 12px;
  background-color: #0079de;
  border-radius: 10px;
  color: #fff;
  line-height: 20px;
  text-align: center;
}
.preview {
  width: 50px;
  height: 20px;
  font-size: 12px;
  background-color: #fff;
  border: 1px solid #0079de;
  border-radius: 10px;
  color: #0079de;
  line-height: 20px;
  text-align: center;
  margin-right: 6px;
}
</style>
